/*
 * @Date: 2022-06-30 14:41:43
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-07-05 17:23:26
 * @FilePath: \taro-music-learn\src\pages\packageA\VideoDetail\index.tsx
 * @Description: VideoDetail
 */
import React, { useEffect, useRef, useState } from "react";
import { Video, View } from "@tarojs/components";
import { useDidShow, useRouter } from "@tarojs/taro";
import {
  fetchVideoDetailInfo,
  fetchVideoUrlByVid,
  fetchMvDetailInfo,
  fetchMvUrlById
} from "@/store/video";
import { useDispatch } from "react-redux";
import "./index.scss";
import { useSelector } from "@/store/hooks";
import Taro from "@tarojs/taro";
import { clearCurrentVedioInfo } from "@/store/video";
import { AtAvatar, AtIcon, AtTag } from "taro-ui";
import { playCountFormat } from "@/utils";
import Comment from "@/components/Comment";
import {
  reqSubMvById,
  reqSubVideoById,
  reqMvCommentById,
  reqHotCommentByType,
  reqLikeByType
} from "@/api/video";
export type TC = {
  content: string;
  commentId: number;
  time: number;
  likedCount: number;
  replyCount: number;
  user: {
    avatarUrl: string;
    nickname: string;
    userId: number;
  };
};
type TCount = {
  likedCount: number;
  commentCount: number;
  shareCount: number;
};
export interface ICommentInfo {
  comments: TC[];
  total: number;
}
export default function index() {
  const backgroundAudioManager = Taro.getBackgroundAudioManager();
  backgroundAudioManager.pause();
  const { VideoState, subVideoList, subSingers } = useSelector(state => ({
    VideoState: state.Video.currrentVideoInfo,
    subVideoList: state.User.subVideoList,
    subSingers: state.User.subSingerList
  }));
  const [isSub, setIsSub] = useState<boolean>(false);
  const [isSubSinger, setIsSubSinger] = useState(false);
  const [isOpened, setIsOpened] = useState(false);
  const [currentComments, setCurrentComments] = useState<{
    comments: TC[];
    more: boolean;
  }>({ comments: [], more: false });
  const [isLike, setIsLike] = useState(false);
  const [CountInfo, setCountInfo] = useState<TCount>({
    likedCount: 0,
    commentCount: 0,
    shareCount: 0
  });
  const currentOffset = useRef(1);
  const router = useRouter();
  const { vid, type } = router.params;
  const dispatch = useDispatch();
  useEffect(() => {
    setCountInfo({
      likedCount: VideoState.likedCount,
      commentCount: VideoState.commentCount,
      shareCount: VideoState.shareCount
    });
  }, [VideoState.commentCount, VideoState.likedCount, VideoState.shareCount]);
  useEffect(() => {
    getDetailData();
    return () => {
      dispatch(clearCurrentVedioInfo(null));
    };
  }, []);
  useDidShow(() => {
    const flag = subVideoList.some(item => {
      return item.vid === vid!;
    });
    const singerFlag = subSingers.some(item => {
      return item.id === VideoState.creator.id;
    });
    setIsSub(flag);
    setIsSubSinger(singerFlag);
  });
  const getDetailData = async () => {
    if (type! === "1") {
      //点击了video
      console.log("进入video");
      fetchHotCommentByType(5);
      dispatch<any>(fetchVideoDetailInfo(vid!));
      dispatch<any>(fetchVideoUrlByVid(vid!));
    } else {
      //点击了mv
      console.log("进入mv", "vid", vid!);
      fetchHotCommentByType(1);
      dispatch<any>(fetchMvDetailInfo(vid!));
      dispatch<any>(fetchMvUrlById(vid!));
    }
  };
  //显示隐藏评论
  const toggleCommentShow = () => {
    setIsOpened(!isOpened);
  };
  //评论关闭
  const onClose = () => {
    setIsOpened(false);
  };
  //评论触底
  const onScrollToLower = () => {
    console.log("触底了");
    if (!currentComments.more) {
      return;
    }
    currentOffset.current = currentOffset.current + 1;
    fetchHotCommentByType(1);
  };
  //获取热门评论
  const fetchHotCommentByType = async (type: number) => {
    console.log("请求vid", vid!);
    let res = await reqHotCommentByType(vid!, type, currentOffset.current);
    console.log("评论数据", res);
    if (res.data.code === 200) {
      const arr = [...currentComments.comments, ...res.data.data.comments];
      setCurrentComments({
        comments: arr,
        more: res.data.data.hasMore
      });
    }
  };
  //收藏
  const subVideoOrMV = async () => {
    if (type! === "1") {
      //video
      const { data } = await reqSubVideoById(vid!, !isSub);
      if (data.code === 200) {
        setIsSub(!isSub);
      }
    } else {
      //mv
      const { data } = await reqSubMvById(vid!, !isSub);
      if (data.code === 200) {
        setIsSub(!isSub);
      }
    }
  };
  //点赞资源
  const fetchLikeByType = async () => {
    let videoType, t;
    type === "1" ? (videoType = 5) : (videoType = 1);
    isLike ? (t = 1) : (t = 0);
    const { data } = await reqLikeByType(vid!, videoType, t);
    console.log(data, "点赞结果");
    if (data.code === 200) {
      setIsLike(!isLike);
      setCountInfo({
        likedCount: VideoState.likedCount + 1,
        commentCount: VideoState.commentCount,
        shareCount: VideoState.shareCount
      });
    }
  };
  return (
    <View id="video-detail-container-unique">
      <View className="video-container">
        <Video
          id="video"
          src={VideoState.url}
          initialTime={0}
          controls={true}
          autoplay={true}
          loop={true}
          muted={false}
        />
      </View>
      <View className="control-btns-container">
        <View className="btn-item" onClick={fetchLikeByType}>
          <AtIcon value="heart-2" color={isLike ? "#ff0000" : "#fff"}></AtIcon>
          {playCountFormat(CountInfo.likedCount)}
        </View>
        <View className="btn-item" onClick={toggleCommentShow}>
          <AtIcon value="message" color="#fff"></AtIcon>
          {playCountFormat(CountInfo.commentCount)}
        </View>
        <View className="btn-item">
          <AtIcon value="share" color="#fff"></AtIcon>
          {playCountFormat(CountInfo.shareCount)}
        </View>
        <View className="btn-item" onClick={subVideoOrMV}>
          <AtIcon
            value={isSub ? "check-circle" : "add-circle"}
            color="#fff"
          ></AtIcon>
          {isSub ? "取消" : "收藏"}
        </View>
      </View>
      <View className="video-other-info-bottom">
        <View className="video-creator-info">
          <View className="left-creator-avatar">
            <AtAvatar circle image={VideoState.creator.avatar}></AtAvatar>
          </View>
          <View className="creator-name">{VideoState.creator.name}</View>
          <AtTag size="small" circle>
            <AtIcon value="add" size={10}></AtIcon>
            {isSubSinger ? "已关注" : "关注"}
          </AtTag>
        </View>
        <View className="video-title">{VideoState.title}</View>
      </View>
      <Comment
        typeId={vid!}
        type={1}
        onScrollToLower={onScrollToLower}
        onClose={onClose}
        isOpened={isOpened}
        comments={currentComments.comments}
        total={VideoState.commentCount}
      ></Comment>
    </View>
  );
}
